import React, { useState, useMemo } from 'react';
import { ShiftChart } from './chart';
import { get_fix, DlgVal } from './ctl';
import { loc, is_empty, d_sort, BtTxt, obj_str, date_to_time, to_date, Btn, useCmd, GridTable, no_del, PanelTitle } from 'sui';
import { useAccess } from 'cache';

const ShiftView = () => {
    const [open_val, openVal] = useState(false);
    const umd = useCmd("file/list/shift");
    const [no_acc] = useAccess();

    const getRow = useMemo(() => {
        if (is_empty(umd.value)) {
            return null;
        }

        const row = [...umd.value];
        d_sort(row, "start");

        return row;
    }, [umd.value]);

    const hDel = (val) => {
        if (no_del()) {
            return;
        }

        umd.update("file/rm/shift", {
            sn: obj_str(val, "sn"),
        });
    };

    const pact = {
        "add": v => openVal(true),
    };

    const act = {
        "add": d => {
            const sn = obj_str(d, "sn");
            d["start"] = date_to_time(d["start"]);
            d["end"] = date_to_time(d["end"]);

            umd.update("file/md/shift", {
                sn: sn,
                v: d,
            });
        }
    };

    const Right = () => (
        <div className="inline-flex">
            <Btn hcmd={() => umd.pact(pact, {start: to_date(), end: to_date()}, "add")} disabled={no_acc("kj")}>{loc("l_239")}</Btn>
        </div>
    );

    const col = [
        {name: loc("l_238"), key: 'e_opt', width: 90, frozen: true, formatter: (props) => {
            const d = props.row;
            return (
                <div className="inline-flex">
                    <BtTxt hcmd={() => hDel(d)} disabled={no_acc("kj")}>{loc("l_237")}</BtTxt>
                </div>
            );
        }},
        {name: loc("l_229"), key: 'name', width: 200, formatter: (props) => {
            const d = props.row;

            const sn = obj_str(d, "sn");
            const fix = get_fix();

            const f = fix.find(t => t.sn === sn);
            if (f) {
                return f.name;
            }

            return "";
        }},
        {name: loc("l_668"), key: 'start', width: 200},
        {name: loc("l_669"), key: 'end', width: 200},
    ];

    return (
        <div className="flex flex-col">
            <PanelTitle cl="gray" left={loc("l_248")} right={<Right/>}/>
            <div className="mt-4 mb-5">
                <ShiftChart data={umd.value}/>
            </div>
            <GridTable high={500} col={col} row={getRow}/>
            <DlgVal open={open_val} hcmd={v => umd.act(act, v)} setOpen={openVal} data={umd.cur} main={umd.value}/>
        </div>
    );
};

export {ShiftView};
